//
//  YWSelectPatrolLocationTableViewController.m
//  maintain
//
//  Created by Kyo on 16/10/10.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWSelectPatrolLocationTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "MJRefresh.h"
#import "YWLoginTool.h"

#import "DOPDropDownMenu.h"

#import "YWApartment.h"
#import "YWFloor.h"
#import "YWLocation.h"
#import "YWBuildingManager.h"

@interface YWSelectPatrolLocationTableViewController ()<DOPDropDownMenuDataSource,DOPDropDownMenuDelegate>{
    YWApartment *currentApartment;
    YWFloor *currentFloor;
    
    NSInteger page;
}
@property (nonatomic, strong) DOPDropDownMenu *menu;
@property (nonatomic, strong) NSMutableArray *menuDataArray;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *selectLocationArray;
@end

@implementation YWSelectPatrolLocationTableViewController
//- (instancetype)init{
//    return [super  initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"selectLocation", nil);
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"finish", nil) style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemEvent:)];
    
    // 创建menu 第一次显示 不会调用点击代理，可以用这个手动调用
    [self.menu selectDefalutIndexPath];
    
    [self setupDataSource];
    [self setupOwnLocationArray];
    [self initTableView];
}
- (void)setupDataSource{
    page = 1;
    [self.dataSource removeAllObjects];
    NSArray *locations = [[YWBuildingManager shareManager] locationWithBuildingId:self.buildingId apartmentId:0 floorId:0 page:page];
    [self.dataSource addObjectsFromArray:locations];
}

- (NSMutableArray *)menuDataArray{
    if (!_menuDataArray) {
        _menuDataArray = [NSMutableArray array];
        
        NSMutableArray *apartmentMut = [NSMutableArray array];
        YWApartment *apartment = [[YWApartment alloc] init];
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        apartment.apartmentName = apartmentShowName.length? apartmentShowName:NSLocalizedString(@"apartment", nil);
        [apartmentMut addObject:apartment];
        
        NSArray *apartmentArray = [[YWBuildingManager shareManager] apartmentWithbuildingId:self.buildingId];
        [apartmentMut addObjectsFromArray:apartmentArray];
        
        NSMutableArray *floorMut = [NSMutableArray array];
        YWFloor *floor = [[YWFloor alloc] init];
        NSString *floorShowName = [YWLoginTool floorShowName];
        floor.floorName = floorShowName.length? floorShowName:NSLocalizedString(@"floor", nil);
        [floorMut addObject:floor];
        
        [_menuDataArray addObject:apartmentMut];
        [_menuDataArray addObject:floorMut];
        //NSArray *floorArray = [[YWBuildingManager shareManager] floorWithApartmentId:self.apartment.apartmentId];
    }
    return _menuDataArray;
}
- (DOPDropDownMenu *)menu{
    if (!_menu) {
        DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:44];
        menu.delegate = self;
        menu.dataSource = self;
        _menu = menu;
    }
    return _menu;
}

- (void)initTableView{
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView setEditing:YES];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
}

- (void)refreshFootor{
    page++;
    [self.dataSource removeAllObjects];
    NSArray *locations = [[YWBuildingManager shareManager] locationWithBuildingId:self.buildingId apartmentId:currentApartment.apartmentId floorId:currentFloor.floorId page:page];
    [self.dataSource addObjectsFromArray:locations];
    [self setupOwnLocationArray];
    
    [self.tableView.mj_footer endRefreshing];
    [self.tableView reloadData];
}

- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu
{
    return self.menuDataArray.count;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column
{
    return column<0 ? 0 : [_menuDataArray[column] count];
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        YWApartment *apartment = _menuDataArray[indexPath.column][indexPath.row];
        return apartment.apartmentName;
    } else if (indexPath.column == 1){
        YWFloor *floor = _menuDataArray[indexPath.column][indexPath.row];
        return floor.floorName;
        
    }
    return nil;
}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfItemsInRow:(NSInteger)row column:(NSInteger)column
{
    return 0;
}

- (NSString *)menu:(DOPDropDownMenu *)menu titleForItemsInRowAtIndexPath:(DOPIndexPath *)indexPath
{
    return nil;
}

- (void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath
{
    if (indexPath.column == 0) {
        YWApartment *apartment = _menuDataArray[indexPath.column][indexPath.row];
        if (currentApartment.apartmentId!=apartment.apartmentId) {
            currentApartment = apartment;
            currentFloor = nil;

            [_menuDataArray removeLastObject];
            NSMutableArray *floorMut = [NSMutableArray array];
            YWFloor *floor = [[YWFloor alloc] init];
            NSString *floorShowName = [YWLoginTool floorShowName];
            floor.floorName = floorShowName.length? floorShowName:NSLocalizedString(@"floor", nil);
            [floorMut addObject:floor];
            
            NSArray *floorArray = [[YWBuildingManager shareManager] floorWithApartmentId:currentApartment.apartmentId];
            [floorMut addObjectsFromArray:floorArray];
            
            [_menuDataArray addObject:floorMut];
            
            //[_menu reloadData];
            //[_menu selectIndexPath:indexPath];
            DOPIndexPath *reloadIndexPath = [DOPIndexPath indexPathWithCol:1 row:0];
            [_menu selectIndexPath:reloadIndexPath];
        }
        
    } else if (indexPath.column == 1){
        YWFloor *floor = _menuDataArray[indexPath.column][indexPath.row];
        currentFloor = floor;
        
    }
    page = 1;
    [self rightNowSelect];
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuseIdentifier = @"selectPatrolLocationReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        cell.textLabel.font = kContentFont;
    }
    YWLocation *location = _dataSource[indexPath.row];
    cell.textLabel.text = [[YWBuildingManager shareManager] areaLocationNobuildingWithId:location.locationId];
    return cell;
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    return _menu;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    YWLocation *location = _dataSource[indexPath.row];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", location.locationId];
    NSArray *array = [[self.selectLocationArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    if (array.count>0) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YWLocation *location = _dataSource[indexPath.row];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", location.locationId];
    NSArray *array = [[self.selectLocationArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    if (array.count==0 && location) {
        [self.selectLocationArray addObject:location];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWLocation *location = _dataSource[indexPath.row];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", location.locationId];
    NSArray *array = [[self.selectLocationArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    if (array.count==1 && location) {
        [self.selectLocationArray removeObject:array[0]];
    }
}

- (void)rightNowSelect{
    [self.dataSource removeAllObjects];
    NSArray *locations = [[YWBuildingManager shareManager] locationWithBuildingId:self.buildingId apartmentId:currentApartment.apartmentId floorId:currentFloor.floorId page:page];
    [self.dataSource addObjectsFromArray:locations];
    
    [self setupOwnLocationArray];
    
    [self.tableView reloadData];
}

- (void)setupOwnLocationArray{
    [self.ownLocationArray enumerateObjectsUsingBlock:^(YWLocation*  _Nonnull location, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", location.locationId];
        NSArray *array = [[_dataSource filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            YWLocation *loca = array[0];
            NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"locationId", loca.locationId];
            NSArray *array = [[self.selectLocationArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
            if (array.count==0 && loca) {
                [self.selectLocationArray addObject:loca];
            }
        }
    }];
}

- (void)rightBarButtonItemEvent:(id)sender{
    //点完成
    if ([self.delegate respondsToSelector:@selector(selectPatrolLocations:)]) {
        [self.delegate selectPatrolLocations:self.selectLocationArray];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)selectLocationArray{
    if (!_selectLocationArray) {
        _selectLocationArray = [NSMutableArray array];
    }
    return _selectLocationArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
